//
//  Data+Additions.swift
//  MGExtensionsKit
//
//  Created by Max on 2019/12/16.
//

import Foundation

public protocol DataConvertible {
    init?(data: Data)
    var data: Data { get }
}

public extension DataConvertible where Self: ExpressibleByIntegerLiteral {
    init?(data: Data) {
        var value: Self = 0
        guard data.count == MemoryLayout.size(ofValue: value) else { return nil }
        _ = withUnsafeMutableBytes(of: &value, { data.copyBytes(to: $0)} )
        self = value
    }

    var data: Data {
        return withUnsafeBytes(of: self) { Data($0) }
    }
}

extension Int : DataConvertible { }
extension Int8 : DataConvertible { }
extension Int16 : DataConvertible { }
extension Int32 : DataConvertible { }
extension Int64 : DataConvertible { }
extension Float : DataConvertible { }
extension Double : DataConvertible { }

public extension Data {
    var JSONObject: Any? {
        do {
            let obj = try JSONSerialization.jsonObject(with: self, options: JSONSerialization.ReadingOptions.init(rawValue: 0))
            return obj
        }catch _ {
            return nil
        }
    }
}
